package com.work.app.controller;




import com.alipay.easysdk.factory.Factory;
import com.work.app.service.AlipayService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hjj
 * @Time 2024/3/10 16:54
 */
@RestController
@Slf4j
@CrossOrigin
@RequestMapping("/pays")
public class AlipayController {
    @Autowired
    private AlipayService alipayService;

    @ApiOperation("调用支付宝接口，返回的是字符串格式的表单")
    @GetMapping("/topay")
    public String pay(
            @ApiParam("交易标记/编号")@RequestParam("subject") String subject,
            @ApiParam("交易金额，BigDecimal型")@RequestParam("money")BigDecimal money) throws Exception {
        return alipayService.toPay(subject, money);
    }

    @ApiOperation("支付回调接口")
    @PostMapping("/notify")
    public String payNotify(HttpServletRequest request) throws Exception{
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) { //判断是否成功
            //获取请求参数
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }
            //支付宝验签
            if(Factory.Payment.Common().verifyNotify(params)){
                System.out.println("支付成功！");
                System.out.println(params);
                //存入区块链操作
            }
            return "success";//success 为标准成功应答
        }else{
            return "cancel";
        }

    }

}
